<script setup lang="ts">
import { ArrowDown } from "@element-plus/icons-vue";

import {
useReformInstallationProject,
useReformInstallationProjectBuildingExport,
useReformInstallationProjectExport
} from "@fl/api/elevator-api";
import { useGetCascadeData } from "@fl/api/elevator-api/verify";
import { SearchForm, SearchTable, SubmitBtn } from "@fl/components";
import { hasPermi } from "@fl/utils/has-permi";
import { cloneDeep } from "lodash-es";
import type { OptionsType, PlusColumn } from "plus-pro-components";
import type { VxeGridProps, VxePagerEvents } from "vxe-table";
// import createApply from "./components/create.vue";
import { useUserStoreWithOut } from "@fl/store/modules/user";
import addOrEdit from "./components/addOrEdit.vue";
import applyDetail from "./components/applyDetail.vue";
import importUnitDialog from "./components/import-unit-dialog.vue";
defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: "inventory-data-list",
});

const userStore = useUserStoreWithOut();
const enterpriseTypeName = userStore.getOrgInfo?.enterpriseTypeName ?? "";
const areaCode = userStore.getOrgInfo?.areaCode ?? "";
const isZone = ref<boolean>(areaCode==='429006000000');
const projectName = ref<string>("");
// 判断是否为区住更局
const isArea = computed(
    () =>
        userStore.getOrgInfo?.enterpriseAccount != "4201" &&
        enterpriseTypeName == "市住更局(电梯加装)"
);
const flagDict = {
    1: "具备加装电梯条件小区",
    2: "未纳入清册小区",
    3: "范围外小区",
};
const flagOptions = [
    { value: 1, label: "具备加装电梯条件小区" },
    { value: 2, label: "未纳入清册小区" },
    { value: 3, label: "范围外小区" },
];
const auditOptions = [
    { value: 1, label: "是" },
    { value: 2, label: "否" },
];
type IinitialState = {
    areaCode?: string;
    streetCode?: string;
    communityCode?: string;
    projectName?: string;
};

const router = useRouter();
const initialState = {
    areaCode: "",
    streetCode: "",
    communityCode: "",
    projectName: "",
};
const state = ref<IinitialState>(cloneDeep(initialState));
const searchConditions = ref<IinitialState>(cloneDeep(initialState));
const detailId = ref<string>("");

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
});

// 级联
const getAreaOptionsParams = computed(() => ({
    targetLabel: "area",
}));
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: "street",
}));
const getCommunityOptionsParams = computed(() => ({
    streetCode: state.value.streetCode,
    targetLabel: "community",
}));
const getProjectOptionsParams = computed(() => ({
    communityCode: state.value.communityCode,
    targetLabel: "project",
    projectName: projectName.value,
}));

const { data: areaOptions } = useGetCascadeData(getAreaOptionsParams);
const { data: streetOptions } = useGetCascadeData(getStreetOptionsParams, "areaCode");
const { data: communityOptions } = useGetCascadeData(
    getCommunityOptionsParams,
    "streetCode"
);
const { data: projectOptions } = useGetCascadeData(
    getProjectOptionsParams,
    "projectName"
);

function projectSearch(keyword) {
    projectName.value = keyword;
}

watch(
    () => state.value.areaCode,
    () => {
        const { communityCode, streetCode, ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

watch(
    () => state.value.streetCode,
    () => {
        const { communityCode, ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

watch(
    () => state.value.communityCode,
    () => {
        const { ...data } = state.value;
        state.value = cloneDeep(data);
    }
);

const params = computed(() => ({
    ...searchConditions.value,
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    orderBy: "create_time", // 根据创建时间排序
    orderType: "desc", // 降序
}));
const detailParams = ref({});
const { data, isLoading } = useReformInstallationProject(params);

const records = ref<any>();
const createVisible = ref<boolean>(false);
const detailVisible = ref<boolean>(false);
const isReadonly = ref<boolean>(false);

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.currentPage = currentPage;
    tablePage.pageSize = pageSize;
};

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records);
        tablePage.total = data.value.total!;

        
        
    }
});

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: "所在区",
        options: areaOptions as OptionsType,
        prop: "areaCode",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        label: "街道",
        options: streetOptions as OptionsType,
        prop: "streetCode",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        label: "社区",
        options: communityOptions as OptionsType,
        prop: "communityCode",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        // fieldProps: {
        //     filterable: true,
        // },
        label: "小区",
        // options: projectOptions as OptionsType,
        prop: "projectName",
        // valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: "小区编号",
        prop: "projectCode",
    },
    {
        colProps: {
            span: 6,
        },
        label: "小区标识",
        options: flagOptions as OptionsType,
        prop: "flag",
        valueType: "select",
    },
    {
        colProps: {
            span: 6,
        },
        label: "核实结果",
        options: auditOptions as OptionsType,
        prop: "auditResult",
        valueType: "select",
    },
];
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: "序号", type: "seq", width: 60 },
        { field: "areaName", title: "所在区" },
        { field: "streetName", title: "街道" },
        { field: "communityName", title: "社区" },
        { field: "projectName", title: "小区" },
        { field: "projectCode", title: "小区编号" },
        { slots: { default: "auditResult" }, title: "核实结果" },
        { slots: { default: "flag" }, title: "小区标识" },
        { field: "buildingNum", title: "楼栋数量", visible:!isZone.value},
        { field: "unitNum", title: "单元数量", visible:!isZone.value},
        { slots: { default: "operate" }, title: "操作", width: 150 },
    ],
});

function submit() {
    searchConditions.value = cloneDeep(state.value);
    resetTablePage();
}

function reset() {
    state.value = cloneDeep(initialState);
    searchConditions.value = cloneDeep(initialState);
    resetTablePage();
}

function resetTablePage() {
    tablePage.currentPage = 1;
    tablePage.pageSize = 10;
}
function add() {
    detailParams.value = {};
    createVisible.value = true;
    isReadonly.value = false;
}
// 编辑：编辑、核实，仅文字不一样
function edit(row) {
    detailParams.value = cloneDeep(row);
    createVisible.value = true;
    isReadonly.value = false;
}
// 核实：仅查看
function check(row) {
    detailParams.value = cloneDeep(row);
    createVisible.value = true;
    isReadonly.value = true;
}
function showDetail(row) {
    // row.addressInfo = row.addressInfo===null?'':row.addressInfo
    detailParams.value = cloneDeep(row);
    detailVisible.value = true;
    detailId.value = String(cloneDeep(row).id);
}
function toBuilding(row) {
    router.push({
        name: "building-list",
        query: {
            id: row.id,
            projectName: row.projectName,
        },
    });
}
const exportParams = computed(() => ({
    ...searchConditions.value,
}));
const {
    isPending: projectPending,
    mutateAsync: projectMutateAsync,
} = useReformInstallationProjectExport(exportParams);

const {
    isPending: buildingPending,
    mutateAsync: buildingMutateAsync,
} = useReformInstallationProjectBuildingExport(exportParams);
async function exportProject() {
    const res = await projectMutateAsync();
    if (res) {
        const objectUrl = URL.createObjectURL(res);
        location.href = objectUrl;
        URL.revokeObjectURL(objectUrl);
    }
}
async function exportProjectBuilding() {
    const res = await buildingMutateAsync();
    if (res) {
        const objectUrl = URL.createObjectURL(res);
        location.href = objectUrl;
        URL.revokeObjectURL(objectUrl);
    }
}
const importVisible = ref(false);
</script>

<template>
    <ElCard class="mb-20" shadow="never">
        <SearchForm
            v-model="state"
            submit-text="搜索"
            :columns="columns"
            @reset="reset"
            @submit="submit"
        >
            <!-- <template #plus-field-projectId>
                <el-select v-model="state.projectId"
                           filterable
                           remote
                           reserve-keyword
                           placeholder="直接搜小区,无需选区域"
                           remote-show-suffix
                           :remote-method="projectSearch"
                >
                    <el-option v-for="item in projectOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template> -->
        </SearchForm>
    </ElCard>

    <ElCard shadow="never">
        <SearchTable
            v-bind="gridOptions"
            v-model:pager="tablePage"
            :loading="isLoading"
            :data="records"
            @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <ElButton v-if="hasPermi('清册数据-新增')" type="primary" @click="add">
                    新增
                </ElButton>
                <SubmitBtn
                    v-if="hasPermi('清册数据-小区导出')"
                    plain
                    type="primary"
                    @click="exportProject"
                    :loading="projectPending"
                >
                    <div class="i-iconamoon:upload size-16" />
                    小区导出
                </SubmitBtn>
                <SubmitBtn
                    v-if="hasPermi('清册数据-楼栋清册导出')"
                    plain
                    type="primary"
                    @click="exportProjectBuilding"
                    :loading="buildingPending"
                >
                    <div class="i-iconamoon:upload size-16" />
                    楼栋清册导出
                </SubmitBtn>
                <ElButton
                    type="primary"
                    v-if="hasPermi('清册数据-导入单元')"
                    @click="importVisible = true"
                    >导入单元</ElButton
                >
            </template>

            <template #flag="{ row }">
                {{ flagDict[row.flag] }}
            </template>

            <template #auditResult="{ row }">
                {{ row.auditResult == 1 ? "是" : row.auditResult == 2 ? "否" : "-" }}
            </template>

            <template #operate="{ row }">
                <div class="flex items-center">
                    <ElButton type="info" text @click="showDetail(row)"> 详情 </ElButton>

                    <el-dropdown
                        v-if="
                            hasPermi('清册数据-编辑') ||
                            hasPermi('清册数据-编辑') ||
                            hasPermi('清册数据-楼栋维护')
                        "
                    >
                        <span class="el-dropdown-link">
                            <el-icon class="el-icon--right">
                                <ArrowDown />
                            </el-icon>
                        </span>

                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item
                                    v-if="
                                        hasPermi('清册数据-编辑') &&
                                        (row?.flag === 1 || row?.flag === 2)
                                    "
                                >
                                    <ElButton type="info" text @click="edit(row)">
                                        编辑
                                    </ElButton>
                                </el-dropdown-item>

                                <el-dropdown-item
                                    v-if="
                                        hasPermi('清册数据-核实') &&
                                        (row?.flag === 2 ||
                                            (row?.flag === 3 && !isArea)) &&
                                        row?.auditResult != 2
                                    "
                                >
                                    <!-- 区住更局只对"未纳入清册小区"的核实权限 -->
                                    <ElButton type="info" text @click="check(row)">
                                        核实
                                    </ElButton>
                                </el-dropdown-item>

                                <el-dropdown-item v-if="hasPermi('清册数据-楼栋维护')">
                                    <ElButton
                                        type="primary"
                                        text
                                        @click="toBuilding(row)"
                                    >
                                        楼栋管理
                                    </ElButton>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </template>
        </SearchTable>
    </ElCard>

    <addOrEdit
        v-model:visible="createVisible"
        v-model:flag="isReadonly"
        v-model:detail="detailParams"
    />

    <applyDetail
        v-model:visible="detailVisible"
        v-model:id="detailId"
        :detail="detailParams"
    />
    <importUnitDialog v-if="importVisible" v-model:show="importVisible" />
</template>

<style scoped>
.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}
</style>
